package com.example.campuslink.viewModel

import android.content.Context
import android.content.Intent
import android.os.Message
import android.widget.Toast
import com.example.campuslink.model.ActJumpData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.ai.AiDao
import com.example.campuslink.commen.db.ai.AiDataBase
import com.example.campuslink.commen.db.comment.CommentDao
import com.example.campuslink.commen.db.comment.CommentData
import com.example.campuslink.commen.db.comment.CommentTable
import com.example.campuslink.commen.db.invitation.InvitationDao
import com.example.campuslink.commen.db.invitation.InvitationData
import com.example.campuslink.commen.db.message.MessageDao
import com.example.campuslink.commen.db.message.MessageData
import com.example.campuslink.commen.db.school.SchoolInfoDao
import com.example.campuslink.commen.db.school.SchoolInfoData
import com.example.campuslink.commen.db.school.SchoolInfoTable
import com.example.campuslink.commen.db.search.SearchDao
import com.example.campuslink.commen.db.search.SearchData
import com.example.campuslink.commen.db.userInfo.UserInfoDao
import com.example.campuslink.commen.db.userInfo.UserInfoData
import com.example.campuslink.commen.db.userNumber.UserNumberDao
import com.example.campuslink.commen.db.userNumber.UserNumberData
import com.example.campuslink.commen.db.userNumber.UserNumberTable
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.ui.activity.SchoolChoiceActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

open class BaseViewModel : ViewModel() {
    lateinit var context: Context

    val actJumpLiveData = MutableLiveData<ActJumpData>()

    protected lateinit var numberDB: UserNumberData
    protected lateinit var schoolInfoDB: SchoolInfoData
    protected lateinit var userNumberDao: UserNumberDao
    protected lateinit var schoolInfoDao: SchoolInfoDao
    protected lateinit var userInfoDB: UserInfoData
    protected lateinit var userInfoDao: UserInfoDao
    protected lateinit var invitationDB: InvitationData
    protected lateinit var invitationDao: InvitationDao
    protected lateinit var messageDB: MessageData
    protected lateinit var messageDao: MessageDao
    protected lateinit var aiDB: AiDataBase
    protected lateinit var aiDao: AiDao
    protected lateinit var searchDB: SearchData
    protected lateinit var searchDao: SearchDao
    protected lateinit var commentDao: CommentDao
    protected lateinit var commentDB: CommentData

    fun initDB(context: Context) {
        numberDB = UserNumberData.getDatabase(context)
        userNumberDao = numberDB.userNumberDao()
        schoolInfoDB = SchoolInfoData.getDatabase(context)
        schoolInfoDao = schoolInfoDB.schoolInfoDao()
        userInfoDB = UserInfoData.getDatabase(context)
        userInfoDao = userInfoDB.userInfoDao()
        invitationDB = InvitationData.getDatabase(context)
        invitationDao = invitationDB.invitationDao()
        messageDB = MessageData.getDatabase(context)
        messageDao = messageDB.messageDao()
        aiDB = AiDataBase.getDatabase(context)
        aiDao = aiDB.aiDao()
        searchDB = SearchData.getDatabase(context)
        searchDao = searchDB.searchDao()
        commentDB = CommentData.getDatabase(context)
        commentDao = commentDB.commentDao()
    }


    // TODO: 自动添加管理员 后续有什么需要改变直接更改这个逻辑
    fun addAdminUser() {
        viewModelScope.launch(Dispatchers.IO) {
            val adminUser = UserNumberTable(
                telNumber = "admin",
                password = "admin",
                username = "管理员"
            )
            if (userNumberDao.getUserNumber("admin") == null) {
                userNumberDao.insertUserNumber(adminUser)
            }
        }
    }

    fun login(username: String, password: String) {
        viewModelScope.launch {
            try {
                // 切换到 IO 线程执行数据库操作
                val userNumber = withContext(Dispatchers.IO) {
                    userNumberDao.getUserNumber(username)
                }

                // 自动切换回主线程处理 UI 逻辑
                if (userNumber != null) {
                    if (userNumber.password == password) {
                        startActivity(
                            Intent(),
                            targetClass = SchoolChoiceActivity::class.java,
                            true
                        )
                        Sp.setString(context, "userNumber", username)
                    } else {
                        Toast.makeText(context, "密码错误", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Sp.setString(context, "registerNumber", username)
                    Toast.makeText(context, "用户不存在,请点击下方注册", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(context, "登录失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }


    /**
     * 启动activity
     */
    @JvmOverloads
    protected fun startActivity(
        targetIntent: Intent? = null,
        targetClass: Class<*>,
        finishCurrent: Boolean = false,
    ) {
        actJumpLiveData.postValue(ActJumpData(targetIntent, targetClass, finishCurrent))
    }


    /**
     * 关闭activity
     */
    protected fun finishActivity() {
        actJumpLiveData.postValue(ActJumpData(null, null, true))
    }
}